package com.csg.ses.common.configuration;

import com.auth0.jwt.JWT;
import com.csg.ses.common.utils.RedisUtil;
import com.csg.ses.entity.ses.SysUserLoginEntity;
import com.csg.ses.service.ses.SysUserLoginService;
import com.csg.ses.vo.login.LoginInfo;
import com.csg.ses.vo.login.UserView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 当前登录UserView参数设置
 * @auther wangjun
 * @date 2020/11/16
 */
@Configuration
public class UserViewResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private SysUserLoginService userLoginService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().equals(UserView.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String token = nativeWebRequest.getHeader("token");
        String loginCode = JWT.decode(token).getAudience().get(0);
        SysUserLoginEntity user = userLoginService.getByLoginCode(loginCode);
        LoginInfo loginInfo = (LoginInfo) redisUtil.get(String.valueOf(user.getLoginId()));
        return loginInfo.getUser();
    }
}